package com.yanqu.road.server.cmd.activity.entername;

import com.yanqu.road.entity.activity.entername.ActivityGroupMatch;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross3.activity.EnterNameProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.manger.activity.entername.EnterNameActivityMgr;
import com.yanqu.road.server.manger.activity.entername.EnterNameCache;
import com.yanqu.road.server.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.S_ENTER_NAME_ALL_NAME_SYNC_FROM_CROSS, desc = "同步整个渠道报名数据(全量)（来自跨服）")
public class EnterNameAllSyncFromCross3Cmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) throws Exception {

        EnterNameProto.ChannelEnterNameAllSyncMsg syncMsg = EnterNameProto.ChannelEnterNameAllSyncMsg.parseFrom(yanQuMessage.getBytes());

        Map<Long, EnterNameCache> cacheMap = new ConcurrentHashMap<>();
        for (EnterNameProto.UserEnterNameMsg enterNameMsg : syncMsg.getNameList()) {
            EnterNameCache cache = new EnterNameCache();
            cache.setUserId(enterNameMsg.getUserId());
            cache.setZoneId(enterNameMsg.getZoneId());
            cacheMap.put(cache.getUserId(), cache);
        }
        EnterNameActivityMgr.cacheEnterName(syncMsg.getActivityId(), cacheMap);

        EnterNameActivityMgr.getLogger().info("enter name cache activityId {}, all user size {}", syncMsg.getActivityId(), cacheMap.size());

        if(syncMsg.getGroupList().size() > 0){
            List<ActivityGroupMatch> list = new ArrayList<>();
            for (EnterNameProto.ChannelEnterNameGroupingMsg groupingMsg : syncMsg.getGroupList()) {
                ActivityGroupMatch match = new ActivityGroupMatch();
                match.setActivityId(syncMsg.getActivityId());
                match.setGroupId(groupingMsg.getGroupId());
                match.setEnemyGroupId(groupingMsg.getEnemyGroupId());
                match.setZoneIdList(groupingMsg.getZoneListList());
                list.add(match);
            }
            EnterNameActivityMgr.getMatchMap().put(syncMsg.getActivityId(), list);
        }
    }
}
